package com.sjb.mianshiya.backfilter;

import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.StrUtil;
import com.sjb.mianshiya.utils.NetUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @Author:sjb
 * @CreateTime:2024-11-21
 * @Description: 对所有Ip进行过滤
 * @Version：1.0
 */
@WebFilter(urlPatterns = "/*",filterName = "blackIpFilter")
@Slf4j
public class BlackIPFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String ipAddress = NetUtils.getIpAddress((HttpServletRequest) request);
        log.info("IP是：{}", ipAddress);
        if (BlackIpUtils.isBlackIp(ipAddress)){
            log.info("在黑名单内");
            response.setContentType("text/json;charset=utf-8");
            response.getWriter().write("{\"errorCode\":\"-1\",\"errorMsg\":\"黑名单IP，禁止访问\"}");
            return;
        }
        chain.doFilter(request, response);
    }
}
